const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const userRoutes = require('./routes/userRoutes');
const messageRoute = require("./routes/messagesRoute");
const { Server } = require('socket.io')

const app = express();
require('dotenv').config();

app.use(cors());
app.use(express.json());

app.use("/api/auth", userRoutes)
app.use("/api/messages", messageRoute)

mongoose.connect(process.env.MONGO_URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}).then(() => {
    console.log('Connected to MongoDB');
}).catch((err) => {
    console.log(err.message);
})

const server = app.listen(process.env.PORT || 5000, () => {
    console.log(`Server is running on port ${process.env.PORT}`);
});

const io = new Server(server, {
    cors: {
        origin: ["http://127.0.0.1:3000", "http://localhost:3000"],
        credentials: true
    }
});

global.onlineUsers = new Map();

io.on('connection', (socket) => {
    console.log('Connected to socket');
    global.chatSocket = socket;

    socket.on('add-user', (userId) => {
        console.log("添加用户: ", userId);
        onlineUsers.set(userId, socket.id);
    });

    socket.on('send-msg', (data) => {
        console.log("发送消息", data);
        const sendUserSocket = onlineUsers.get(data.to);
        if (sendUserSocket) {
            socket.to(sendUserSocket).emit('receive-msg', data.msg);
        }
    });

    socket.on('disconnect', () => {
        console.log('Disonnected to socket');
    });
});
